package com.wuseguang.springcloud.JdbcTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.entity.Student;
import com.wuseguang.springcloud.entity.Teacher;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.HaiweidaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
@Repository
public class HaiweidaCooperativeSchoolJdbc extends BaseTemplate {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 同步学校部门
     *
     * @param schoolId
     * @return
     */
    public String haiweidaDepartment(String schoolId) {


        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, schoolId);
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }

        }

        //查询学校年级
        sql = "select id,`name`,0 `no`,'student' type from grade where school_id = ? ";
        List<Map<String, Object>> list = queryListMap(sql, schoolId);
        //循环年级
        for (Map<String, Object> mapTwo : list) {
            //年级id
            String id = mapTwo.get("id").toString();
            sql = "select id,`name`,0 `no`,'student' type  from classes where grade_id = ?";
            List<Map<String, Object>> listTwo = queryListMap(sql, id);
            mapTwo.put("children", listTwo);
        }

        try {
            String s =HaiweidaUtil.departmentSynchronization(JSON.toJSON(list).toString(), map.get("token").toString());
            //转成json
            JSONObject josn = JSON.parseObject(s);
            //把结果添加到数据库
            inserthaiweidaSynLog(josn, "dpt",JSON.toJSON(list).toString(),Integer.valueOf(schoolId),"");
        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");
        }
        return "0";
    }

    /**
     * 海威达同步学生
     *
     * @param list
     * @return
     */
    public String haiweidaStudent(List<Student> list) {
        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, list.get(0).getSchoolId());
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }
        }

        List<Map<String, Object>> mapList = new ArrayList<>();
        //循环
        for (Student s : list) {

            Map<String, Object> mapTow = new HashMap<>();
            mapTow.put("id", s.getId());
            mapTow.put("name", s.getStudentName());
            mapTow.put("stuNo", s.getStuNo());
            mapTow.put("type", "student");
            mapTow.put("dptId", s.getClassId());
            mapTow.put("schoolCode", map.get("school_code"));
            mapTow.put("sex", s.getSex() + 1);
            mapTow.put("cardId", s.getCardNumber());
            mapList.add(mapTow);
        }

        try {
            String s = HaiweidaUtil.userSynchronization(JSON.toJSON(mapList).toString(), map.get("token").toString());
            //转成json
            JSONObject josn = JSON.parseObject(s);
            //把结果添加到数据库
            inserthaiweidaSynLog(josn, "user",JSON.toJSON(mapList).toString(),list.get(0).getSchoolId(),"0");

        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");

        }
        return "0";
    }

    /**
     * 海威达同步教师
     *
     * @param list
     * @return
     */
    public String haiweidaTeacher(List<Teacher> list) {
        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, list.get(0).getSchoolId());
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }
        }

        List<Map<String, Object>> mapList = new ArrayList<>();
        //循环
        for (Teacher t : list) {

            Map<String, Object> mapTow = new HashMap<>();
            mapTow.put("id", t.getId());
            mapTow.put("name", t.getName());
            mapTow.put("stuNo", "");
            mapTow.put("type", "teacher");
            mapTow.put("dptId", "0");
            mapTow.put("schoolCode", map.get("school_code"));
            mapTow.put("sex", t.getSex() + 1);
            mapList.add(mapTow);
        }

        try {
            String s = HaiweidaUtil.userSynchronization(JSON.toJSON(mapList).toString(), map.get("token").toString());
            //转成json
            JSONObject josn = JSON.parseObject(s);
            //把结果添加到数据库
            inserthaiweidaSynLog(josn, "user",JSON.toJSON(mapList).toString(),list.get(0).getSchoolId(),"1");
        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");
        }

        return "0";
    }


    /**
     * 海威达同步学生人脸1.0
     *
     * @param facesId  人脸id
     * @param schoolId 学生id
     * @return
     */
    public String haiweidaStudentFaces(String facesId, String schoolId) {

        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, schoolId);
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }
        }
        sql = "select student_id userId ,url photoUrl,'student' type from student_faces where id in(?)";

        List<Map<String, Object>> list = queryListMap(sql, facesId);

        try {
            HaiweidaUtil.faceSynchronization(JSON.toJSON(list).toString(), map.get("token").toString());
        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");
        }

        return "0";
    }


    /**
     * 海威达同步学生人脸2.0
     *
     * @param facesMap 人脸Map
     * @param schoolId 学生id
     * @return
     */
    public String haiweidaStudentFacesTwo(Map<String, Object> facesMap, String schoolId) {

        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, schoolId);
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }

        }

        List<Map<String, Object>> list = new ArrayList<>();
        list.add(facesMap);
        try {

            String s =HaiweidaUtil.faceSynchronization(JSON.toJSON(list).toString(), map.get("token").toString());
            //转成json
            JSONObject josn = JSON.parseObject(s);
            //把结果添加到数据库
            inserthaiweidaSynLog(josn, "photo",JSON.toJSON(list).toString(),Integer.valueOf(schoolId),"0");
        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");

        }

        return "0";
    }

    /**
     * 海威达同步学生人脸2.0
     *
     * @param list     人脸集合
     * @param schoolId 学生id
     * @return
     */
    public String haiweidaStudentFacesTwo(List<Map<String, Object>> list, String schoolId) {

        //查询这个学校是否是合作学校
        String sql = "select id,school_code,user_name,password,school_id,token,exp_time,uuid" +
                " from haiweida_cooperative_school where school_id = ?";
        Map<String, Object> map = null;
        try {
            map = queryMap(sql, schoolId);
        } catch (Exception e) {
            logger.info("无合作学校");
            return "1";
        }
        //获取时间
        Date date = DateUtil.strToDateLong(map.get("exp_time").toString(), "yyyy-MM-dd HH:mm:ss");
        //判断有效时间小于当前时间
        if (date.getTime() < System.currentTimeMillis()) {
            //刷新token
            Map<String, Object> tokenMap = tokenMapTwo(map);
            if (!StringUtils.isEmpty(tokenMap)) {
                map.put("token", tokenMap.get("token").toString());
            }

        }


        try {

            String s =HaiweidaUtil.faceSynchronization(JSON.toJSON(list).toString(), map.get("token").toString());
            //转成json
            JSONObject josn = JSON.parseObject(s);
            //把结果添加到数据库
            inserthaiweidaSynLog(josn, "photo",JSON.toJSON(list).toString(),Integer.valueOf(schoolId),"0");
        } catch (Exception e) {
            logger.info("同步失败是因为token过期验证失败报错401");
        }

        return "0";
    }

    /**
     * 属性token重新修改
     *
     * @param map
     * @return
     */
    public Map<String, Object> tokenMap(Map<String, Object> map) {
        try {
            //刷新token
            Map<String, Object> tokenMap = HaiweidaUtil.refreshToken(map.get("uuid").toString(), map.get("token").toString());

            String uuid = tokenMap.get("uuid").toString();
            String expTime = tokenMap.get("expTime").toString();
            String token = "JWT " + tokenMap.get("token").toString();
            //获取时间
            Date d = new Date(System.currentTimeMillis() + (Integer.valueOf(expTime) * 1000) - 60000);
            //修改过期token
            String sql = "UPDATE `haiweida_cooperative_school` SET `token` = ?, `exp_time` = ?, `uuid` = ? WHERE `id` = ? ";
            updateByParameter(sql, token, d, uuid, map.get("id").toString());

            return tokenMap;
        } catch (Exception e) {
            logger.info("token 为空");
            return null;
        }
    }


    /**
     * 属性token重新修改
     *
     * @param map
     * @return
     */
    public Map<String, Object> tokenMapTwo(Map<String, Object> map) {
        try {
            //刷新token
            Map<String, Object> tokenMap = HaiweidaUtil.login(map.get("school_code").toString(),
                    map.get("user_name").toString(), map.get("password").toString());

            String uuid = tokenMap.get("uuid").toString();
            String expTime = tokenMap.get("expTime").toString();
            String token = "JWT " + tokenMap.get("token").toString();
            //获取时间
            Date d = new Date(System.currentTimeMillis() + (Integer.valueOf(expTime) * 1000) - 60000);
            //修改过期token
            String sql = "UPDATE `haiweida_cooperative_school` SET `token` = ?, `exp_time` = ?, `uuid` = ? WHERE `id` = ? ";
            updateByParameter(sql, token, d, uuid, map.get("id").toString());
            tokenMap.put("token", "JWT " + tokenMap.get("token"));
            return tokenMap;
        } catch (Exception e) {
            logger.info("token 为空");
            return null;
        }
    }


    public void inserthaiweidaSynLog(JSONObject josn, String type,String content,Integer schoolId,String state) {

        String sql = "INSERT INTO `haiweida_syn_log`(`content`, `uuid`, `syn_results`, `code`, `school_id`, `type`,`state`, `add_time`) " +
                "VALUES (?, ?, ?,?, ?, ?,?, now())";


        String code  = josn.get("code").toString();
        String uuid = null;
        //判断是否同步成功
        if("2000".equals(code)){
            JSONObject dataJson = JSON.parseObject(josn.get("data").toString());
            //uuid
            uuid = dataJson.get("uuid").toString();
        }
        //插入数据
        updateByParameter(sql,content,uuid,josn.toString(),code,schoolId,type,state);
    }
}
